package cn.sskxyz.security.resource.config;

import cn.sskxyz.security.resource.authorization.RbacPermissionValidator;
import cn.sskxyz.security.resource.property.ResourceServerSystemProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;


@Configuration
@EnableResourceServer
@EnableConfigurationProperties({ResourceServerSystemProperty.class})
public class ResourceServerConfigure extends ResourceServerConfigurerAdapter {

    @Autowired(required = false)
    private DefaultTokenServices tokenService;

    @Autowired
    private ResourceServerSystemProperty systemProperty;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenServices(tokenService);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        AccessDecisionVoter decisionVoter = new RbacAccessDecisionVoter(new RbacPermissionValidator(systemProperty));

        http.authorizeRequests().antMatchers("/**")
                .access("isAuthenticated() and hasAuthority(\"xxx\") and hasRole(\"yyy\")")
                .anyRequest()
                .authenticated()
                .withObjectPostProcessor(new ResourcePostProcessor(decisionVoter))
            .and()
                .formLogin().disable()
                .httpBasic().disable()
                .csrf().disable();
    }
}
